from sqlalchemy.orm import Session
from schema import Machine_Data_Processing_schema
from model import Machine_Data_Processing_model



def get_Machine_Data_Processing(db: Session, ID: int):
    return db.query(Machine_Data_Processing_model.Machine_data_processing).filter(Machine_Data_Processing_model.Machine_data_processing.ID == ID).first()


def get_all_Machine_Data_Processing(db: Session):
    return db.query(Machine_Data_Processing_model.Machine_data_processing).all()


def delete_Machine_Data_Processing(db: Session, ID):
    to_delete = db.query(Machine_Data_Processing_model.Machine_data_processing).filter(Machine_Data_Processing_model.Machine_data_processing.ID == ID)
    deleted = to_delete.delete()
    if deleted == 0:
        return None
    else:
        db.commit()
        return True


def create_Machine_Data_Processing(db: Session, Machine_Data_Processing: Machine_Data_Processing_schema.Machine_data_processing):
    db_Machine_Data_Processing = Machine_Data_Processing_model.Machine_data_processing(
        MachineID=Machine_Data_Processing.MachineID,
        SensorID=Machine_Data_Processing.SensorID,
        AIModelID=Machine_Data_Processing.AIModelID,
        RawDataJSON=Machine_Data_Processing.RawDataJSON,
        AnalysisResultJSON=Machine_Data_Processing.AnalysisResultJSON,
        RawDataRetrievalTime=Machine_Data_Processing.RawDataRetrievalTime,
        ProcessingTime=Machine_Data_Processing.ProcessingTime,
        Remarks=Machine_Data_Processing.Remarks,
    )
    db.add(db_Machine_Data_Processing)
    db.commit()
    db.refresh(db_Machine_Data_Processing)
    return db_Machine_Data_Processing


def update_Machine_Data_Processing(db: Session, ID, field_name, new_value):
    db_Machine_Data_Processing = db.query(Machine_Data_Processing_model.Machine_data_processing).filter(Machine_Data_Processing_model.Machine_data_processing.ID == ID).first()
    setattr(db_Machine_Data_Processing, field_name, new_value)
    db.commit()
    db.refresh(db_Machine_Data_Processing)
    return db_Machine_Data_Processing
